//3.3 /lib/code2/main_data35.dart
//bottomNavigationBar配制底部导航栏菜单
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:badges/badges.dart' as badges;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/bean/bean_global.dart';
import 'package:flutter_learn_vi/src/common/global.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/page/bloc/bloc_select_page.dart';
import 'package:flutter_learn_vi/src/page/common/app_upgrade.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/home/new/custom_bottom_appbar.dart';
import 'package:flutter_learn_vi/src/page/home/new/v2_home_item_page.dart';
import 'package:flutter_learn_vi/src/page/login/kuangdeng/kuang_deng_login2_page.dart';
import 'package:flutter_learn_vi/src/page/mine/new/v2_mine_main_page.dart';
import 'package:flutter_learn_vi/src/page/mine/question_model.dart';
import 'package:flutter_learn_vi/src/page/news/news_detaile_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:mobpush_plugin/mobpush_custom_message.dart';
import 'package:mobpush_plugin/mobpush_notify_message.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:notification_permissions/notification_permissions.dart';

import '../../../bean/bean_app_setting.dart';
import '../../../bean/bean_user.dart';
import '../../catalogue/catalogue_notia_page.dart';
import '../../mine/account/account_center_page.dart';
import '../../mine/account/controller/account_center_controller.dart';
import '../../study/cache/CustomCacheManager.dart';
import '../../train/tain_main_page.dart';
import '../../train/train_notification_recoder_page.dart';
import 'controller/HomeMainV2PageController.dart';

//lib/src/page/home/home_main_page.dart
//主页面的根布局
class HomeMainV2Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeMainState();
  }
}

class _HomeMainState extends State<HomeMainV2Page>
    with MineQuestionModel, WidgetsBindingObserver {
  //当前显示页面的标签
  int _tabIndex = 0;

  //[PageView]使用的控制器
  PageController _pageController = PageController();

  //底部导航栏使用到的图标
  List<Icon> _normalIcon;
  List<BottomNavigationBarItem> _bottomlist;
  List<Widget> _normalHomeBody;

  //底部导航栏使用到的标题文字
  List<String> _normalTitle;

  StreamSubscription _homeSubscription;

  /// 点击去打开通知权限时会设置为 true
  bool _isPushOpen = false;

  HomeMainV2PageController _homeMainV2PageController;

  @override
  void initState() {
    super.initState();
    flutterBuglyFunction();
    _homeSubscription =
        rootStreamController.stream.listen(streamListenFunction);
    _homeMainV2PageController = Get.put(HomeMainV2PageController());
    initHomeData();
    getQuestion();
    getStartPic();
    WidgetsBinding.instance.addObserver(this);
    Future.delayed(Duration.zero, () {
      _homeMainV2PageController.requeshNoReadMessageCunnt();
      checkAppVersion(context);
    });

    initFunction();
    // initPlatformState();
  }

  void flutterBuglyFunction() async {}

  ///主要是用来检查推送通知权限
  initFunction() async {
    bool result = await checkPush();
    if (result) {
      UserBean userBean = UserHelper.getInstance.userBean;
      if (userBean != null) {
        initMob();
      }
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      if (_isPushOpen) {
        initFunction();
      }
    }
  }

  //检查通知权限
  Future<bool> checkPush({bool background: false}) async {
    PermissionStatus status =
        await NotificationPermissions.getNotificationPermissionStatus();
    switch (status) {
      case PermissionStatus.denied:
        break;
      case PermissionStatus.granted:
        LogUtils.e("有推送通知权限");
        return true;
        break;
      case PermissionStatus.unknown:
        break;
      case PermissionStatus.provisional:
        break;
      default:
        return null;
    }
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: Text("打开推送通知权限，可以获取最新的内容通知！！！"),
            actions: <Widget>[
              TextButton(
                  onPressed: () {
                    _isPushOpen = false;
                    Navigator.pop(context);
                  },
                  child: Text("暂不需要")),
              TextButton(
                  onPressed: () {
                    _isPushOpen = true;
                    NotificationPermissions.requestNotificationPermissions(
                        iosSettings: const NotificationSettingsIos(
                            sound: true, badge: true, alert: true));
                    Navigator.pop(context);
                  },
                  child: Text("去打开权限"))
            ],
          );
        });
    return false;
  }

  void initMob() async {
    if (Platform.isIOS) {
      //设置地区：regionId 默认0（国内），1:海外
      MobpushPlugin.setRegionId(0);
      MobpushPlugin.registerApp(
          "3680e1fc40f73", "d10f44c2e89b9f8a86939cacc5fdd816");
    }

    String sdkVersion;
    String _registrationId;
    // try {
    //   sdkVersion = await MobpushPlugin.getSDKVersion();
    // } on PlatformException {
    //   sdkVersion = 'Failed to get platform version.';
    // }
    try {
      MobpushPlugin.getRegistrationId().then((Map<String, dynamic> ridMap) {
        print(ridMap);
        setState(() {
          _registrationId = ridMap['res'].toString();
          print('------>#### registrationId: ' + _registrationId);
        });
      });
    } on PlatformException {
      _registrationId = 'Failed to get registrationId.';
    }
    if (Platform.isIOS) {
      MobpushPlugin.setCustomNotification();
      MobpushPlugin.setAPNsForProduction(true);
    }
    MobpushPlugin.addPushReceiver(_onEvent, _onError);
    //上传隐私协议许可
    MobpushPlugin.updatePrivacyPermissionStatus(true).then((value) {
      print(">>>>>>>>>>>>>>>>>>>updatePrivacyPermissionStatus:" +
          value.toString());
    });
    UserBean userBean = UserHelper.getInstance.userBean;
    int mineId = userBean.mineId;
    int userId = userBean.userId;
    List<String> tags = ["$mineId,$userId"];
    String department = userBean.department;
    if (department != null && department.length > 0) {
      tags.add(department);
    }

    MobpushPlugin.addTags(tags).then((Map<String, dynamic> tagsMap) {
      String res = tagsMap['res'];
      String error = tagsMap['error'];
      print(">>>>>>>>>>>>>>>>>>>>>>>>>>> addTags -> res: $res error: $error");
    });
    MobpushPlugin.setAlias("$userId").then((Map<String, dynamic> aliasMap) {
      String res = aliasMap['res'];
      String error = aliasMap['error'];
      // String errorCode = aliasMap['errorCode'];
      print(">>>>>>>>>>>>>>>>>>>>>>>>>>> setAlias -> res: $res error: $error");
    });
  }

  void _onEvent(Object event) {
    LogUtils.e("接收到消息 _onEvent");
    Map<String, dynamic> eventMap = json.decode(event as String);
    Map<String, dynamic> result = eventMap['result'];
    int action = eventMap['action'];

    switch (action) {
      case 0:
        MobPushCustomMessage message =
            new MobPushCustomMessage.fromJson(result);
        showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                content: Text(message.content),
                actions: <Widget>[
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text("确定"))
                ],
              );
            });
        break;
      case 1:
        MobPushNotifyMessage message =
            new MobPushNotifyMessage.fromJson(result);
        messageController(message);
        break;
      case 2:
        MobPushNotifyMessage message =
            new MobPushNotifyMessage.fromJson(result);
        break;
    }
  }

  void _onError(Object event) {
    LogUtils.e("接收到消息 _onError");
  }

  Widget buildRight() {
    //集团权限
    if (UserHelper.getInstance.userBean.userBlocType == 1) {
      return Container(
        child: InkWell(
          onTap: () {
            NavigatorUtils.pushPage(
                context,
                BlocSelectPage(
                  isShowAppBar: true,
                ));
          },
          child: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.only(right: 8),
            child: Text(
              "切换",
              textAlign: TextAlign.center,
              style: TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.blue,
              ),
            ),
            // child: Image.asset(
            //   "assets/images/2.0x/keixingjituan.jpeg",
            //   width: 44,
            // ),
          ),
        ),
      );
    } else {
      return Container();
    }
  }

  void streamListenFunction(GlobalBean globalBean) {
    //刷新消息
    LogUtils.e("消息传递 刷新消息 ${globalBean.data.toString()}");
    if (globalBean.code == 202) {
      //清除缓存用户信息
      UserHelper.getInstance.exitLogin();
      //跳转登录页面 矿灯学院
      NavigatorUtils.openPageByFade(
        context,
        KuangDengLogin2Page(),
        mills: 1000,
        endMills: 800,
        isReplace: true,
      );
    } else if (globalBean.code == 203) {
      getQuestion();
      getStartPic();
    } else if (globalBean.code == 205) {
      Map<String, String> data = globalBean.data;
      CustomCacheManager.cacheVideo(url: data["url"], key: data["key"]);
    }
  }

  initHomeData() {
    checkPassData();
  }

  void checkPassData() {
    _normalTitle = [
      "首页",
      "通知通告",
      "积分管理",
      "培训",
      "个人中心",
    ];
    _normalIcon = [
      Icon(Icons.home),
      Icon(Icons.pending_sharp),
      Icon(Icons.markunread_mailbox_outlined),
      Icon(Icons.list),
      Icon(Icons.people)
    ];

    _normalHomeBody = <Widget>[
      //第一个页面
      HomeItemMainV2Page(),
      //第二个页面
      CatalogueNotiaMainPage(),
      AccountCenterPage(
        tag: "homeItem",
        showTitle: true,
      ),
      // MainStudyPage(),
      //个人中心
      MineMainV2Page(),
    ];

    _bottomlist = <BottomNavigationBarItem>[
      new BottomNavigationBarItem(label: _normalTitle[0], icon: _normalIcon[0]),
      new BottomNavigationBarItem(icon: _normalIcon[1], label: _normalTitle[1]),
      new BottomNavigationBarItem(icon: _normalIcon[2], label: _normalTitle[2]),
      new BottomNavigationBarItem(icon: _normalIcon[3], label: _normalTitle[3]),
    ];
  }

  @override
  void dispose() {
    super.dispose();
    //移除监听
    _homeSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    bool show02 = false;
    AppSettingBean appSettingBean = UserHelper.getInstance.appSettingBean;
    UserBean userBean = UserHelper.getInstance.userBean;
    if (userBean != null) {
      show02 = userBean.isIosCheck == 1;
    }

    if (show02) {
      _normalHomeBody = <Widget>[
        //第一个页面
        HomeItemMainV2Page(),
        //第二个页面
        CatalogueNotiaMainPage(),
        //AccountCenterPage(tag: "homeItem"),
        // MainStudyPage(),
        //个人中心
        MineMainV2Page(),
      ];
    }

    //UserBean userBean = UserHelper.getInstance.userBean;
    // 是否是培训班主任 默认0不是 ；1为是
    int isDirector = userBean.isDirector;
    //是否是培训教师  默认0不是 ；1为是
    int isTeacher = userBean.isTeacher;

    // 班主任  0 APP内容全部显示  1  只显示工作台
    int showDirectorWorkBench = userBean.showDirectorWorkBench;
    // 教师  0 APP内容全部显示  1  只显示工作台
    int showTeacherWorkBench = userBean.showTeacherWorkBench;
    if (isDirector == 1 || isTeacher == 1) {
      if (showDirectorWorkBench == 1 || showTeacherWorkBench == 1) {
        return Scaffold(body: MineMainV2Page());
      }
    }

    //Scaffold 用来搭建页面的主体结构
    LogUtils.e("当前页面 $_tabIndex");
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: (_tabIndex == 0)
          ? AppBar(
              leading: buildHeaderImage(),
              title: buildHeader(),
              actions: [
                buildRight(),
                GestureDetector(
                  child: buildBadgeWidget(),
                  onTap: () async {
                    await Get.to(() => TrainNotificationRecoderPage());
                    _homeMainV2PageController.requeshNoReadMessageCunnt();
                  },
                ),
              ],
            )
          : null,
      //页面的主内容区
      //可以是单独的StatefulWidget 也可以是当前页面构建的如Text文本组件
      body: PageView(
        //设置PageView不可滑动切换
        physics: NeverScrollableScrollPhysics(),
        //PageView的控制器
        controller: _pageController,
        //PageView中的三个子页面
        children: _normalHomeBody,
      ),
      //底部导航栏
      bottomNavigationBar: BottomAppBar(
        //背景颜色
        color: Colors.white,
        //自定义底部菜单栏
        child: CustomBottomAppBar(
          clickCallBack: (int index) {
            _pageController.jumpToPage(index);
            LogUtils.e("切换PageView中的页面显示-- $index");
            _tabIndex = index;
            if (index == 0) {
              _homeMainV2PageController.requeshNoReadMessageCunnt();
            } else if (index == 2) {
              if (Get.isRegistered<AccountCenterController>(tag: "homeItem")) {
                Get.find<AccountCenterController>(tag: "homeItem")
                    .initRequest();
              }
            }
            setState(() {});
          },
        ),
      ),
    );
  }

  Widget buildBadgeWidget() {
    return GetBuilder(
      id: "homeBadget",
      builder: (HomeMainV2PageController controller) {
        int noReadBadgetCount = controller.noReadBadgetCount;
        if (noReadBadgetCount == 0) {
          return Container(
            padding: EdgeInsets.all(10),
            child: Image.asset("assets/images/3.0x/message_icon.png"),
          );
        }
        return Container(
          padding: EdgeInsets.all(10),
          child: badges.Badge(
            position: badges.BadgePosition.topStart(top: -8, start: 24),
            badgeContent: Text(
              '${noReadBadgetCount > 99 ? noReadBadgetCount.toString() + "+" : noReadBadgetCount}',
              style: TextStyle(fontSize: 10, color: Colors.white),
            ),
            child: Image.asset("assets/images/3.0x/message_icon.png"),
          ),
        );
      },
    );
  }

  //lib/src/page/home/home_main_page.dart
  //构建底部导航栏
  BottomNavigationBar buildBottomNavigation() {
    //创建一个 BottomNavigationBar
    return new BottomNavigationBar(
      selectedItemColor: Colors.red,
      unselectedItemColor: Colors.grey,
      items: _bottomlist,
      //显示效果
      type: BottomNavigationBarType.fixed,
      //当前选中的页面
      currentIndex: _tabIndex,
      //图标的大小
      iconSize: 24.0,
      //点击事件
      onTap: (index) {
        //切换PageView中的页面显示
        LogUtils.e("切换PageView中的页面显示 $index");
        _pageController.jumpToPage(index);
        _tabIndex = index;
        setState(() {});
      },
    );
  }

  Widget buildHeader() {
    if (UserHelper.getInstance.mineBean == null) {
      return Container();
    }
    return Text(
      UserHelper.getInstance.mineBean.name,
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.w500,
        color: Colors.blueGrey,
      ),
    );
  }

  Widget buildHeaderImage() {
    if (UserHelper.getInstance.mineBean == null) {
      return Image.asset(
        "assets/images/3.0x/bg_header.png",
        fit: BoxFit.fill,
        width: 33,
        height: 33,
      );
    }
    String url = UserHelper.getInstance.mineBean.logoUrl;

    if (url == null || url.length == 0) {
      Image.asset(
        "assets/images/3.0x/bg_header.png",
        fit: BoxFit.fill,
        width: 33,
        height: 33,
      );
    }
    return Stack(
      alignment: Alignment.center,
      children: [
        Material(
          color: Colors.transparent,
          child: ClipOval(
            child: CachedNetworkImage(
              imageUrl: url,
              fit: BoxFit.fill,
              width: 33,
              height: 33,
            ),
          ),
        )
      ],
    );
  }

  void messageController(MobPushNotifyMessage message) {
    String title = message.title;
    Map<String, dynamic> extrasMap = message.extrasMap;

    try {
      if (extrasMap != null) {
        // // final map = jsonDecode(pushModel);
        // String pushModelString = map["pushModel"];
        // final map2 = jsonDecode(pushModelString);
        final url = extrasMap["url"];
        final newsId = extrasMap["newsId"];
        final trainId = extrasMap["trainId"];
        _homeMainV2PageController.readMessage(trainId);
        showCommonAlertDialog(
            context: context,
            contentMessag: title,
            selectText: "去查看",
            cancleText: "不感兴趣",
            selectCallBack: () {
              if (newsId == null && trainId == null) {
                ToastUtils.showToast("暂无详情查看");
                return;
              }
              if (newsId != null) {
                Get.to(() => NewsDetailePage(
                      newsId: int.parse(newsId),
                      screenSize: MediaQuery.of(context).size,
                    ));
              } else if (trainId != null) {
                Get.to(() => TrainMainPage());
              }
            });
      }
    } catch (e) {
      LogUtils.e("极光推送消息解析失败");
    }
  }
}
